package com.sec.etech.ism.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmCommonService;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmTaskService;
import com.sec.etech.sys.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsmGetPartsDrawingFileServiceImpl implements IsmMethodService {
    @Resource
    IsmTaskService ismTaskService;
    @Resource
    IsmCommonService ismCommonService;

    public IsmGetPartsDrawingFileServiceImpl(){}

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception{
        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        JSONObject result = new JSONObject();
        JSONObject object = this.checkAndGetData(businessParams);
        Map<String, Object> partsMap = null;
        if (StringUtil.isNotEmpty(object.getString("material_no"))) {
            String sql = "select partsid,partsnum from prod_parts where active=1 and parts_SAPnum=?";
            partsMap = slaveJdbcTemplate.queryForMap(sql, object.getString("material_no"));
        }else if(StringUtil.isNotEmpty(object.getString("partsNum"))) {
            String sql = "select partsid,partsnum from prod_parts where active=1 and partsnum=?";
            partsMap = slaveJdbcTemplate.queryForMap(sql, object.getString("partsNum"));
        }
        //获取零件图纸信息
        List<String> drawingList = ismCommonService.getPartsDrawingFile(partsMap.get("partsid").toString(), partsMap.get("partsnum").toString());
        ismTaskService.deleteTaskByParams(sysCode, serviceCode, serviceCode, null, businessParams.getString(SignatureConstant.INPUT_PARAMS));
        result.put("flag", "success");
        result.put("data", drawingList);
        return result;
    }
    //入参检查
    private JSONObject checkAndGetData(JSONObject busParams) throws BusinessMessage{
        JSONObject object = busParams.getJSONObject(SignatureConstant.INPUT_PARAMS);
        if(StringUtil.isEmpty(object.getString("material_no")) && StringUtil.isEmpty(object.getString("partsNum"))){
            throw new BusinessMessage("请求中零件物料号和零件图号不能全部为空，请检查参数！");
        }

        return object;
    }

    @Override
    public String methodName(){
        return "getPartsDrawingFile";
    }
}
